package com.qf.application.service.impl;

import com.qf.application.commons.exception.BusinessException;
import com.qf.application.entity.Menu;
import com.qf.application.entity.User;
import com.qf.application.entity.UserRoleVo;
import com.qf.application.mapper.IAllotMapper;
import com.qf.application.service.IAllotService;
import com.qf.application.vo.RoleMenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
public class AllotServiceImpl implements IAllotService {

    @Autowired
    private IAllotMapper allotMapper;

    @Override
    public List<Integer> getMenuIdListByRoleId(Integer roleId) {
        return allotMapper.getMenuIdListByRoleId(roleId);
    }

    /**
     * 1、为什么需要servic层
     * 2、没有用过事务，项目怎么用事务
     *
     * @param roleMenuVo
     * @return
     */
    @Override
    @Transactional
    public Boolean roleAddMenu(RoleMenuVo roleMenuVo) {
        // 1.在插入之前先清空这个角色的权限
        allotMapper.deleteRoleMenuByRoleId(roleMenuVo);

//        int i = 10 / 0;
        // 2.在做插入操作
        if (roleMenuVo.getMenuIdList() != null && roleMenuVo.getMenuIdList().size() > 0) {
            allotMapper.insertRoleMenu(roleMenuVo);
        }
        return true;
    }

    @Override
    public List<User> getUserByRoleId(Integer roleId) {
        return allotMapper.getUserByRoleId(roleId);
    }

    @Override
    public Boolean userAddRole(UserRoleVo roleVo) {
        Set<Integer> userRoleList = allotMapper.getUserRoleList(roleVo);
        if (!userRoleList.add(roleVo.getRoleId())) {
            throw new BusinessException(3001, "选择的用户已经存在当前角色");
        }
        return allotMapper.userAddRole(roleVo) > 0 ? true : false;
    }

    @Override
    public void removeUserRole(Integer roleId, Integer userId) {
        allotMapper.removeUserRole(roleId, userId);
    }

    @Override
    public Set<String> getUserUrl(Integer userId) {
        return allotMapper.getUserUrl(userId);
    }
}
